/**
 * 关注关系API库
 * @author HalRui
 * @version 1.0.0
 * @description 提供关注关系相关的业务逻辑和数据操作
 * @date 2025年9月27日
 */

const Follow = require('../models/follows-model');
const UserInfos = require('../models/userinfos-model');

/**
 * 关注用户
 * @param {number} followerId - 关注者用户ID
 * @param {number} followingId - 被关注者用户ID
 * @returns {Object} 操作结果
 */
async function followUser(followerId, followingId) {
    try {
        // 验证用户是否存在
        const follower = await UserInfos.findByUserId(followerId);
        const following = await UserInfos.findByUserId(followingId);

        if (!follower.success || !following.success) {
            return {
                success: false,
                message: "用户不存在"
            };
        }

        // 检查用户状态
        if (follower.message.status !== 'active' || following.message.status !== 'active') {
            return {
                success: false,
                message: "用户状态异常，无法关注"
            };
        }

        // 创建关注关系
        const result = await Follow.createFollow(followerId, followingId);
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 取消关注用户
 * @param {number} followerId - 关注者用户ID
 * @param {number} followingId - 被关注者用户ID
 * @returns {Object} 操作结果
 */
async function unfollowUser(followerId, followingId) {
    try {
        const result = await Follow.unfollow(followerId, followingId);
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 检查关注状态
 * @param {number} followerId - 关注者用户ID
 * @param {number} followingId - 被关注者用户ID
 * @returns {Object} 关注状态
 */
async function checkFollowStatus(followerId, followingId) {
    try {
        const result = await Follow.checkFollowStatus(followerId, followingId);
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 获取关注列表（我关注的人）
 * @param {number} userId - 用户ID
 * @param {number} page - 页码
 * @param {number} limit - 每页数量
 * @returns {Object} 关注列表
 */
async function getFollowingList(userId, page = 1, limit = 20) {
    try {
        const result = await Follow.getFollowingList(userId, page, limit);
        
        if (result.success && result.message.follows.length > 0) {
            // 获取被关注用户的详细信息
            const followingIds = result.message.follows.map(follow => follow.followingId);
            const users = await UserInfos.find({
                userId: { $in: followingIds },
                isDeleted: false
            }).select('userId username nickname avatar userLevel');

            // 合并关注信息和用户信息
            const followsWithUserInfo = result.message.follows.map(follow => {
                const user = users.find(u => u.userId === follow.followingId);
                return {
                    ...follow.getSafeJSON(),
                    userInfo: user ? user.isSafeJSON() : null
                };
            });

            result.message.follows = followsWithUserInfo;
        }

        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 获取粉丝列表（关注我的人）
 * @param {number} userId - 用户ID
 * @param {number} page - 页码
 * @param {number} limit - 每页数量
 * @returns {Object} 粉丝列表
 */
async function getFollowersList(userId, page = 1, limit = 20) {
    try {
        const result = await Follow.getFollowersList(userId, page, limit);
        
        if (result.success && result.message.followers.length > 0) {
            // 获取关注者用户的详细信息
            const followerIds = result.message.followers.map(follow => follow.followerId);
            const users = await UserInfos.find({
                userId: { $in: followerIds },
                isDeleted: false
            }).select('userId username nickname avatar userLevel');

            // 合并关注信息和用户信息
            const followersWithUserInfo = result.message.followers.map(follow => {
                const user = users.find(u => u.userId === follow.followerId);
                return {
                    ...follow.getSafeJSON(),
                    userInfo: user ? user.isSafeJSON() : null
                };
            });

            result.message.followers = followersWithUserInfo;
        }

        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 获取用户关注统计
 * @param {number} userId - 用户ID
 * @returns {Object} 关注统计
 */
async function getFollowStats(userId) {
    try {
        const result = await Follow.getFollowStats(userId);
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 批量检查关注状态
 * @param {number} followerId - 关注者用户ID
 * @param {Array} followingIds - 被关注者用户ID数组
 * @returns {Object} 批量关注状态
 */
async function batchCheckFollowStatus(followerId, followingIds) {
    try {
        const result = await Follow.batchCheckFollowStatus(followerId, followingIds);
        return result;
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

/**
 * 获取互相关注的用户列表
 * @param {number} userId - 用户ID
 * @param {number} page - 页码
 * @param {number} limit - 每页数量
 * @returns {Object} 互相关注列表
 */
async function getMutualFollows(userId, page = 1, limit = 20) {
    try {
        // 获取我关注的人
        const myFollowing = await Follow.find({
            followerId: userId,
            status: 1,
            isDeleted: false
        }).select('followingId');

        if (myFollowing.length === 0) {
            return {
                success: true,
                message: {
                    mutualFollows: [],
                    pagination: {
                        page,
                        limit,
                        total: 0,
                        pages: 0
                    }
                }
            };
        }

        const followingIds = myFollowing.map(f => f.followingId);

        // 查找也关注我的人
        const skip = (page - 1) * limit;
        const mutualFollows = await Follow.find({
            followerId: { $in: followingIds },
            followingId: userId,
            status: 1,
            isDeleted: false
        })
        .sort({ createAt: -1 })
        .skip(skip)
        .limit(limit);

        const total = await Follow.countDocuments({
            followerId: { $in: followingIds },
            followingId: userId,
            status: 1,
            isDeleted: false
        });

        // 获取用户信息
        if (mutualFollows.length > 0) {
            const mutualUserIds = mutualFollows.map(f => f.followerId);
            const users = await UserInfos.find({
                userId: { $in: mutualUserIds },
                isDeleted: false
            }).select('userId username nickname avatar userLevel');

            const mutualFollowsWithUserInfo = mutualFollows.map(follow => {
                const user = users.find(u => u.userId === follow.followerId);
                return {
                    ...follow.getSafeJSON(),
                    userInfo: user ? user.isSafeJSON() : null
                };
            });

            return {
                success: true,
                message: {
                    mutualFollows: mutualFollowsWithUserInfo,
                    pagination: {
                        page,
                        limit,
                        total,
                        pages: Math.ceil(total / limit)
                    }
                }
            };
        }

        return {
            success: true,
            message: {
                mutualFollows: [],
                pagination: {
                    page,
                    limit,
                    total: 0,
                    pages: 0
                }
            }
        };
    } catch (error) {
        return {
            success: false,
            message: error.message
        };
    }
}

module.exports = {
    followUser,
    unfollowUser,
    checkFollowStatus,
    getFollowingList,
    getFollowersList,
    getFollowStats,
    batchCheckFollowStatus,
    getMutualFollows
};